package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
)

func getVoice(w http.ResponseWriter, r *http.Request) {
	text := r.URL.Query().Get("voice")
	if len(text) == 0 || text == "" {
		result := map[string]interface{}{
			"code": 400,
			"msg":  "Param of the request is empty (text)",
			"data": "",
		}
		json.NewEncoder(w).Encode(result)
	}
	audioBytes, err := base64.StdEncoding.DecodeString(text)
	if err != nil {
		result := map[string]interface{}{
			"code": 500,
			"msg":  "Failed to Base64 decode",
			"data": "",
		}
		json.NewEncoder(w).Encode(result)
	}
	audioBuffer := bytes.NewBuffer(audioBytes)
	result := map[string]interface{}{
		"code": 200,
		"msg":  "Success",
		"data": audioBuffer.Bytes(),
	}
	json.NewEncoder(w).Encode(result)
	// 准备播放音频
	// 缓存数据
	if err := ioutil.WriteFile("./tmp/voice.wav", audioBuffer.Bytes(), 0644); err != nil {
		log.Fatal(err)
	}
}

func main() {
	http.HandleFunc("/voice", getVoice)

	err := http.ListenAndServe(":11451", nil)
	if err != nil {
		log.Fatal(err)
	}
}
